# -*- coding: utf-8 -*-
import sys
import re   
import xbmc
import elementtree.ElementTree as ET
from t0mm0.common.addon import Addon
from t0mm0.common.net import Net


addon_id = 'plugin.video.bronxbicoXXX'
addon = Addon(addon_id, sys.argv)
net = Net()

#find the mode
mode = addon.queries['mode']
#find the URL to resolve if a video has been clicked
url = addon.queries.get('url','')

def main():
	xbmc.executebuiltin("Container.SetViewMode(500)")
	categories()

def links(url):
	xbmc.executebuiltin("Container.SetViewMode(500)")
	#Grab the playlist file
	videos = net.http_GET(url).content.encode('utf-8')
	play_list_regex = re.compile(ur'type=(.+?)\nname=(.+?)\nthumb=(.+?)\nURL=(.*)')
	videos_list = []
	for v in play_list_regex.finditer(videos):
		l_type,name,thumb,url = v.groups()
		#only add videos ignore playlists
		if 'video' in l_type:
			videos_list.append({'name':name,'thumb':thumb,'url':url})
	totalitems = len(videos_list)	
	for video in videos_list:
		addon.add_item({'mode': 3, 'url': video['url']}, {'title': video['name']}, img = video['thumb'], resolved=False,total_items=totalitems, item_type='video', is_folder=False)

def categories():
	url = 'https://video-bronx.googlecode.com/svn/trunk/list/plugin_playlist.plx'
	cats = net.http_GET(url).content.encode('utf-8')
	cats = ET.fromstring(cats)
	for cat in cats.getchildren():
		name = cat.find('name').text
		thumb = cat.find('img').text
		url = cat.find('url').text
		addon.add_directory({'mode':2,'url':url}, {'title': name}, img=thumb, fanart='', total_items=0, is_folder=True)

def resolve(url):
	import commonresolvers
	stream_url = commonresolvers.get(url)
	if stream_url:
		addon.resolve_url(stream_url)
		addon.log('Resolved URL',level=1)

if mode=='main':
	main()		
elif mode =='2':
	links(url)
elif mode =='3':
	resolve(url)

addon.end_of_directory()
